package com.cloud.cloudvideo.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.amqp.core.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cloud.cloudvideo.entity.Plupload;
import com.cloud.cloudvideo.entity.SysUser;
import com.cloud.cloudvideo.entity.VideoMedia;
import com.cloud.cloudvideo.entity.VideoMediaPo;
import com.cloud.cloudvideo.mapper.VideoMediaMapper;
import com.cloud.cloudvideo.rabbitmq.MsgProducer;
import com.cloud.cloudvideo.service.VideoMediaService;
import com.cloud.cloudvideo.utils.ConfigUtil;
import com.cloud.cloudvideo.utils.Constants;
import com.cloud.cloudvideo.utils.PluploadUtil;
import com.cloud.cloudvideo.utils.VideoTypeConvert;
import com.cloud.cloudvideo.utils.VideoUtil;
import com.rabbitmq.client.Channel;

@Service
public class VideoMediaServiceImpl implements VideoMediaService {

	@Autowired
	private VideoMediaMapper videoMediaMapper;
	@Autowired
	private Plupload plupload;
	@Autowired
	private MsgProducer msgProducer;

	@Override
	public List<VideoMediaPo> list(String mediaorginalname) {
		VideoMedia vm = new VideoMedia();
		vm.setMediaorginalname(mediaorginalname);
		vm.setMeidiastatus(Constants.VIDEO_STATUS_UNDELETE);
		List<VideoMediaPo> list = videoMediaMapper.findVideoAndCate(vm);
		return list;
	}

	@Override
	public void modifyVideoMedia(VideoMedia vm) {
		if (null != vm.getId()) {
			videoMediaMapper.updateByPrimaryKeySelective(vm);
		} else {
			Subject subject = SecurityUtils.getSubject();
			SysUser user = (SysUser) subject.getPrincipal();
			vm.setUploadtime(new Date());
			vm.setUploaduser(user.getId() + "");
			videoMediaMapper.insertSelective(vm);
			msgProducer.sendMsg(vm.getId() + "");
		}

	}

	@Override
	public void uploadFile(Plupload upload, String key) {
		// 文件存储路径
		File keyFile = new File(plupload.getUploadPath() + "\\" + key);
		String fileName = keyFile.getName();
		File dir = keyFile.getParentFile();
		try {
			// 上传文件
			PluploadUtil.upload(upload, dir, fileName);
			// 判断文件是否上传成功（被分成块的文件是否全部上传完成）
			if (PluploadUtil.isUploadFinish(upload)) {
				System.out.println(upload.getName() + "文件上传完成");
			}

		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void del(Long id) {
		VideoMedia media = videoMediaMapper.selectByPrimaryKey(id);
		media.setMeidiastatus(Constants.VIDEO_STATUS_DELETE);
		videoMediaMapper.updateByPrimaryKeySelective(media);
	}

	@Override
	public VideoMediaPo videoInfo(Long id) {
		VideoMediaPo po = videoMediaMapper.findVideoAndCateById(id);
		return po;
	}

	@Override
	public void transforMedia(Channel channel, Message message) {
		byte[] content = message.getBody();
		String id = new String(content);
		try {
			if (content != null && !"".equals(content)) {
				VideoMedia video = videoMediaMapper.selectByPrimaryKey(Long.parseLong(id));
				String videoPath = video.getMediaorginalpath();
				String type = videoPath.substring(videoPath.lastIndexOf(".") + 1);
				int duration;
				String tsPath = null;
				String m3u8Path;
				String m3u8URL;
				String mp4Path= videoPath;
				switch (type) {
				case "mp3":
					duration = VideoUtil.processImgWindows(videoPath, ConfigUtil.getFfmpeg(), 1);
//					// 转换Ts
//					tsPath = VideoUtil.transcodingTSByLinux(videoPath, ConfigUtil.getFfmpeg());
//					// 转换m3u8
//					m3u8Path = VideoUtil.transcodingM3U8ByLinux(tsPath, ConfigUtil.getFfmpeg());
//					m3u8URL = m3u8Path.replace('\\', '\\').replace(ConfigUtil.getProfile(), ConfigUtil.getVideourl());
					
					break;
				case "mp4":
					duration = VideoUtil.processImgWindows(videoPath, ConfigUtil.getFfmpeg(), 1);
//					tsPath = VideoUtil.transcodingMp4Windows(videoPath, ConfigUtil.getFfmpeg());
//					// 转换Ts
//					tsPath = VideoUtil.transcodingTSByLinux(videoPath, ConfigUtil.getFfmpeg());
//					// 转换m3u8
//					m3u8Path = VideoUtil.transcodingM3U8ByLinux(tsPath, ConfigUtil.getFfmpeg());
//					m3u8URL = m3u8Path.replace('\\', '\\').replace(ConfigUtil.getProfile(), ConfigUtil.getVideourl());
					break;
				case "avi":
					mp4Path = VideoTypeConvert.AviToMp4(videoPath.replace("/", "\\"));
					duration = VideoUtil.processImgWindows(mp4Path, ConfigUtil.getFfmpeg(), 1);
					// 转换Ts
//					tsPath = VideoUtil.transcodingTSByLinux(mp4Path, ConfigUtil.getFfmpeg());
//					// 转换m3u8
//					m3u8Path = VideoUtil.transcodingM3U8ByLinux(tsPath, ConfigUtil.getFfmpeg());
//					m3u8URL = m3u8Path.replace('\\', '\\').replace(ConfigUtil.getProfile(), ConfigUtil.getVideourl());
					break;
				default:
					mp4Path = VideoTypeConvert.toMp4(videoPath);
					duration = VideoUtil.processImgWindows(mp4Path, ConfigUtil.getFfmpeg(), 1);
					// 转换Ts
//					tsPath = VideoUtil.transcodingTSByLinux(mpPath, ConfigUtil.getFfmpeg());
					// 转换m3u8
//					m3u8Path = VideoUtil.transcodingM3U8ByLinux(tsPath, ConfigUtil.getFfmpeg());
//					m3u8URL = m3u8Path.replace('\\', '\\').replace(ConfigUtil.getProfile(), ConfigUtil.getVideourl());
				}

				// 更新视频时长和资源文件
//				video.setMediam3u8path(m3u8Path);
				video.setMediatspath(mp4Path);
//				video.setMediaplayurl(m3u8URL); 
				video.setMeidiaduration(duration);
				video.setIstranscode(1);
				videoMediaMapper.updateByPrimaryKeySelective(video);
				VideoUtil.processImgWindows(videoPath, ConfigUtil.getFfmpeg(), 10);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			VideoMedia video = videoMediaMapper.selectByPrimaryKey(Long.parseLong(id));
			video.setIstranscode(-1);
			videoMediaMapper.updateByPrimaryKeySelective(video);
//            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
			e.printStackTrace();
		}

	}

}
